package com.ruoyi.project.wechatprogram.menu.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.project.wechatprogram.weekend.domain.WxWeekend;
import com.ruoyi.project.wechatprogram.weekend.service.IWxWeekendService;
import com.ruoyi.project.wechatprogram.wxcategory.domain.WxCategory;
import com.ruoyi.project.wechatprogram.wxcategory.service.IWxCategoryService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.wechatprogram.menu.domain.WxMenu;
import com.ruoyi.project.wechatprogram.menu.service.IWxMenuService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 菜单列Controller
 * 
 * @author csx
 * @date 2020-03-27
 */
@Controller
@RequestMapping("/wechatprogram/menu")
public class WxMenuController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(WxMenuController.class);

    private String prefix = "wechatprogram/menu";

    @Autowired
    private IWxMenuService wxMenuService;

    @Autowired
    private IWxCategoryService wxCategoryService;

    @Autowired
    private IWxWeekendService wxWeekendService;

    @RequiresPermissions("wechatprogram:menu:view")
    @GetMapping()
    public String menu()
    {
        return prefix + "/menu";
    }

    /**
     * 查询菜单列列表
     */
    @RequiresPermissions("wechatprogram:menu:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxMenu wxMenu)
    {
        startPage();
        List<WxMenu> list = wxMenuService.selectWxMenuList(wxMenu);
        return getDataTable(list);
    }

    /**
     * 根据种类id查询菜单列列表
     */
    @RequiresPermissions("wechatprogram:menu:listByCategory")
    @PostMapping("/listByCategory")
    @ResponseBody
    public AjaxResult listByCategory(Integer categoryId, Integer weekendId)
    {
        // 查询选中的餐品种类
        List<WxMenu> list = wxMenuService.selectWxMenuListByCategoryId(categoryId);
        // 查询选中的餐品类型
        WxWeekend weekend = new WxWeekend();
        weekend.setWeekendId(weekendId);
        weekend.setCategoryId(categoryId);
        List<WxWeekend> weekendList = wxWeekendService.selectWxWeekendList(weekend);
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < weekendList.size(); j++) {
                if (list.get(i).getId().equals(weekendList.get(j).getMenuId())) {
                    list.get(i).setFlag(true);
                    break;
                } else {
                    list.get(i).setFlag(false);
                }
            }
        }
        return AjaxResult.success(list);
    }

    /**
     * 导出菜单列列表
     */
    @RequiresPermissions("wechatprogram:menu:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WxMenu wxMenu)
    {
        List<WxMenu> list = wxMenuService.selectWxMenuList(wxMenu);
        ExcelUtil<WxMenu> util = new ExcelUtil<WxMenu>(WxMenu.class);
        return util.exportExcel(list, "menu");
    }

    /**
     * 新增菜单列
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        List<WxCategory> categoryList = wxCategoryService.selectWxCategoryList(new WxCategory());
//        List<Pets> list = petsService.selectPetsList(new Pets());
        mmap.put("categoryList", categoryList);
        Map<Object, Object> map = new HashMap<>();
        for(WxCategory category : categoryList){
            map.put(category.getId(), category);
        }
        mmap.put("list", JSONObject.toJSON(map));

        return prefix + "/add";
    }

    /**
     * 新增保存菜单列
     */
    @RequiresPermissions("wechatprogram:menu:add")
    @Log(title = "菜单列", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@RequestParam("menuName")String menuName,@RequestParam("file")MultipartFile file,@RequestParam("menuDescription")String menuDescription)
    {
        WxMenu wxMenu = new WxMenu();
        try
        {
            if (!file.isEmpty())
            {
                String menuPictureUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
                wxMenu.setMenuName(menuName);
                wxMenu.setMenuDescription(menuDescription);
                wxMenu.setMenuPictureUrl(menuPictureUrl);
                wxMenu.setMenuStatus(WxMenu.MENU_STATUS_DOWN);
                if (wxMenuService.insertWxMenu(wxMenu) > 0)
                {
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改菜单失败！", e);
            return error(e.getMessage());
        }
    }


    /**
     * 修改菜单列
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
    {
        WxMenu wxMenu = wxMenuService.selectWxMenuById(id);
        mmap.put("wxMenu", wxMenu);
        return prefix + "/edit";
    }

    /**
     * 修改保存菜单列
     */
    @RequiresPermissions("wechatprogram:menu:edit")
    @Log(title = "菜单列", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@RequestParam("menuId")Integer menuId,@RequestParam("menuName")String menuName,@RequestParam("file")MultipartFile file,@RequestParam("menuDescription")String menuDescription)
    {
        WxMenu wxMenu = new WxMenu();
        try
        {
            if (!file.isEmpty())
            {
                String menuPictureUrl = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
                wxMenu.setId(menuId);
                wxMenu.setMenuName(menuName);
                wxMenu.setMenuDescription(menuDescription);
                wxMenu.setMenuPictureUrl(menuPictureUrl);
                wxMenu.setMenuStatus(WxMenu.MENU_STATUS_DOWN);
                if (wxMenuService.updateWxMenu(wxMenu) > 0)
                {
                    return success();
                }
            }
            return error();
        }
        catch (Exception e)
        {
            log.error("修改菜单失败！", e);
            return error(e.getMessage());
        }

//        return toAjax(wxMenuService.updateWxMenu(wxMenu));
    }

    /**
     * 删除菜单列
     */
    @RequiresPermissions("wechatprogram:menu:remove")
    @Log(title = "菜单列", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        AjaxResult ajaxResult = wxMenuService.deleteWxMenuByIds(ids);
        return ajaxResult;
    }


    /**
     * 餐品上架
     */
    @RequiresPermissions("wechatprogram:menu:publish")
    @Log(title = "菜单列", businessType = BusinessType.UPDATE)
    @PostMapping("/publishMenu/{id}")
    @ResponseBody
    public AjaxResult publishMenu(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        WxMenu wxMenu = new WxMenu();
        wxMenu.setId(id);
        wxMenu.setMenuStatus(WxMenu.MENU_STATUS_UP);
        wxMenuService.updateWxMenu(wxMenu);
        return AjaxResult.success("餐品上架成功");
    }
    /**
     * 餐品下架
     */
    @RequiresPermissions("wechatprogram:menu:unpublish")
    @Log(title = "菜单列", businessType = BusinessType.UPDATE)
    @PostMapping("/unPublishMenu/{id}")
    @ResponseBody
    public AjaxResult unPublishMenu(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        WxMenu wxMenu = new WxMenu();
        wxMenu.setId(id);
        wxMenu.setMenuStatus(WxMenu.MENU_STATUS_DOWN);
        AjaxResult ajaxResult = wxMenuService.updateWxMenuNew(wxMenu);
        return ajaxResult;
    }

    /**
     * 批量上架菜单
     */
    @RequiresPermissions("wechatprogram:menu:batchUp")
    @Log(title = "菜单列", businessType = BusinessType.DELETE)
    @PostMapping( "/batchUp")
    @ResponseBody
    public AjaxResult batchUp(String ids)
    {
        return toAjax(wxMenuService.batchUpMenuByIds(ids));
    }

    /**
     * 批量下架菜单
     */
    @RequiresPermissions("wechatprogram:menu:batchDown")
    @Log(title = "菜单列", businessType = BusinessType.DELETE)
    @PostMapping( "/batchDown")
    @ResponseBody
    public AjaxResult batchDown(String ids)
    {
        return toAjax(wxMenuService.batchDownMenuByIds(ids));
    }


}
